<template>
	<AdaptiveNavBar title="我的订单" :showBack="true" :showHome="false" backgroundColor="#f27b1d" />
	<view class="content-area" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
		<view class="mine-order">
			<!-- 订单状态标签页 -->
			<!-- <view class="order-tabs" :style="{ top: $navbarUtil.getNavbarTotalHeightRpx() }"> -->
			<view class="order-tabs" :style="{ top: statusBarHeight + navbarHeight + 'px' }">
				<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
					:class="{ active: currentTab === index }" @click="switchTab(index)">
					<view class="tab-content">
						<up-icon v-if="tab.icon" :name="tab.icon" :size="20"
							:color="currentTab === index ? '#f27b1d' : '#999'" class="tab-icon">
						</up-icon>
						<text class="tab-title">{{ tab.title }}</text>
						<view v-if="tab.num > 0" class="tab-num">{{ tab.num }}</view>
					</view>
				</view>
			</view>

			<!-- 订单列表内容 -->
			<view class="order-content" :style="{ marginTop: statusBarHeight + navbarHeight + 70 + 'px' }">
				<view class="tabs-content">
					<view class="page-section">

						<!-- 订单列表 -->
						<view v-if="orderList?.length" class="order-list">
							<view v-for="(order, index) in orderList" :key="order.id || index" class="order-card">
								<!-- 订单头部 -->
								<view class="order-header">
									<view class="header-left">
										<view class="header-tag">

										</view>
										<text class="merchant-name">{{ order.ppVO?.name || '研学营' }}</text>
										<text class="play-icon">▶</text>
									</view>
									<view class="header-right">
										<view class="status-badge">
											<text class="status-text">{{ getStatusText(order.order.status) }}</text>
										</view>
										<view v-if="order.countdown" class="countdown-badge">
											<text class="countdown-text">{{ order.countdown }}</text>
										</view>
									</view>
								</view>

								<!-- 产品信息 -->
								<view class="order-product-card">
									<ProductCard :info="getProductInfo(order)" :orderMode="true" />
								</view>

								<!-- 已选班期 -->
								<view v-if="order.periodVO" class="selected-period">
									<!-- <image class="period-icon" src="/static/6.jpg" mode="aspectFit"></image> -->
									<u-icon name="calendar" size="24"></u-icon>
									<text class="period-label">已选班期：</text>
									<text class="period-date">{{ order.periodVO.yearDate }}年{{ order.periodVO.monthDate
										}}月{{
											order.periodVO.dayDate }}日</text>
								</view>
								<!-- 参营人员 -->
								<view v-if="order.camperVOS && order.camperVOS.length" class="participants-section">
									<view class="section-header">
										<!-- <text class="cuIcon-peoplefill"></text> -->
										<u-icon name="account-fill" size="24"></u-icon>
										<text class="section-title">参营人员</text>
									</view>
									<view class="participants-list">
										<view v-for="(camper, pIndex) in order.camperVOS" :key="pIndex"
											class="participant-item">
											<view class="participant-info">
												<text class="participant-name">{{ camper?.name }}</text>
												<text :class="getGenderIcon(camper?.idCard)"></text>
												<text class="gender-badge">♂</text>
												<!-- <text class="age-badge">♀</text> -->
												<text class="age-badge">{{ camper?.age }}岁+</text>
												<text class="participant-type" v-if="camper.age < 18">儿童</text>
												<text class="participant-type" v-else>成人</text>
											</view>
											<view class="warning-icon">
												<text class="cuIcon-warning">!</text>
											</view>
										</view>
									</view>
								</view>

								<!-- 订单底部 -->
								<view class="order-footer" v-if="order.order.status === 0">
									<view class="total-amount">
										<text class="amount-value">¥{{ order.order.totalAmount || 0 }}</text>
										<text class="amount-label">订单金额</text>
									</view>

									<view class="action-buttons">
										<button class="btn-cancel" @click="cancelOrder(order)">
											取消订单
										</button>

										<button class="btn-cancel">
											修改订单
										</button>

										<button class="btn-pay" @click="goToPay(order)">
											去支付
										</button>
									</view>
								</view>


								<view class="order-footer" v-if="order.order.status === 1">
									<view class="amount-info">
										<text class="amount-info-label">已支付订单金额</text>
										<text class="amount-info-value">¥{{ order.order.totalAmount || 0 }}</text>
									</view>

									<view class="action-buttons-one" v-if="order.order.status === 0">
										<view class="more">
											更多
										</view>

										<view class="action-buttons-one-right">
											<button class="btn-sumit">
												更改班期
											</button>

											<button class="btn-sumit">
												退款/售后
											</button>
										</view>
									</view>
								</view>

								<view class="order-footer" v-if="order.order.status === 2">
									<view class="amount-info">
										<text class="amount-info-label">已支付订单金额</text>
										<text class="amount-info-value">¥{{ order.order.totalAmount || 0 }}</text>
									</view>

									<view class="action-buttons-one" v-if="order.order.status === 0">
										<view class="more">
											更多
										</view>

										<view class="action-buttons-one-right">
											<button class="btn-cancel">
												退款/售后
											</button>

											<button class="btn-pay">
												确认完成
											</button>
										</view>
									</view>
								</view>

							</view>
						</view>
						<!-- 空状态 -->
						<view v-else class="empty-state">
							<text class="empty-icon">📋</text>
							<text class="empty-text">暂无订单</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import {
	request
} from '@/utils/request.js';
import ProductCard from '@/components/ProductCard.vue';

export default {
	name: 'order',
	components: {
		ProductCard
	},
	data() {
		return {
			statusBarHeight: 0,
			navbarTotalHeight: 0,
			navbarHeight: 0,

			tabs: [{
				title: '待付款',
				icon: 'bag',
				status: 0,
				num: 0
			},
			{
				title: '待使用',
				icon: 'calendar',
				status: 1,
				num: 0
			},
			{
				title: '待评价',
				icon: 'star',
				status: 3,
				num: 0
			},
			{
				title: '已退款/售后',
				icon: 'reload',
				status: [6, 7],
				num: 0
			},
			{
				title: '其他',
				icon: 'list',
				status: [4, 5],
				num: 0
			}
			],
			currentTab: 0,
			status: 0,
			//接收到的订单集合
			orderList: []
		}
	},
	methods: {
		// 根据订单数据生成产品信息
		getProductInfo(order) {
			if (!order) {
				return {};
			}
			const productInfo = {
				// 接送信息
				pickupInfo: order.periodVO?.saleArea || '',

				// 行程信息
				mergedItineraries: [{
					details: [{
						items: [{
							address: order.ppVO?.specificItinerary?.[0]?.items?.[0]
								?.address || '',
						}]
					}]
				}],

				// 主要产品信息
				mainInfo: {
					price: order.periodVO?.price || 0,
					productSpu: {
						mainImage: order.ppVO?.mainImage || '',
						title: order.ppVO?.title || "",
						minYearOld: order.ppVO?.minYearOld || "",
						maxYearOld: order.ppVO?.maxYearOld || "",
						price: order.periodVO?.price || ""
					},
					productSku: {
						title: order.ppVO?.title || "",
						minYearOld: order.ppVO?.minYearOld || "",
						maxYearOld: order.ppVO?.maxYearOld || "",
						price: order.periodVO?.price || ""
					},
				},

				// 渠道和标签信息
				ChannelName: order.ppVO?.name || "",
				// TagName: order.periodVO?.saleArea || "",

				// 兼容ProductCard组件的默认字段
				Title: order.ppVO?.title || "",
				Amount: order.order?.totalAmount || 0,
				NianLing: `${order.ppVO?.minYearOld || "3"}-${order.ppVO?.maxYearOld || "18"}岁`,
				ShiChang: "1日",
				Address: order.ppVO?.specificItinerary?.[0]?.items?.[0]?.address || '',

				// 可选日期
				availableDates: []
			};

			return productInfo;
		},

		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		// 根据身份证号获取性别图标
		getGenderIcon(idCard) {
			// 检查身份证号是否有效
			if (!idCard || idCard.length < 17) {
				// 默认返回女性图标
				return 'cuIcon-female';
			}

			// 获取第17位数字（索引为16）
			const genderDigit = parseInt(idCard.charAt(16));

			// 奇数为男性，偶数为女性
			return genderDigit % 2 === 1 ? 'cuIcon-male' : 'cuIcon-female';
		},


		// 显示更多选项
		showMore() {
			uni.showActionSheet({
				itemList: ['联系客服', '订单帮助', '意见反馈'],
				success: (res) => {
					console.log('选择了第' + (res.tapIndex + 1) + '个按钮')
				}
			})
		},

		// 切换标签页
		async switchTab(index) {
			if (index == 3) {
				uni.navigateTo({
					url: '/public/order/afterSaleOrder'
				});
				return
			}
			this.currentTab = index


			// 根据标签页获取对应状态的订单
			this.getOrderByStatus(index)
			// 重新获取所有状态的订单数量以保持数据同步
			await this.getAllOrderCounts()
		},

		// 根据状态获取订单
		async getOrderByStatus(tabIndex) {
			const tab = this.tabs[tabIndex]
			const statuses = Array.isArray(tab.status) ? tab.status : [tab.status]

			// 如果是数组状态，需要获取所有状态的订单并合并
			if (statuses.length === 1) {
				// 单个状态，直接获取
				this.getOrder(statuses[0])
			} else {
				// 多个状态，需要合并结果
				try {
					const promises = statuses.map(status =>
						request({
							url: `/orders/status?status=${status}`,
							method: 'GET'
						})
					)

					const results = await Promise.all(promises)

					// 合并所有结果
					let allOrders = []
					results.forEach(res => {
						if (res.code === 200 && res.data) {
							allOrders = allOrders.concat(res.data)
						}
					})

					this.orderList = allOrders
					console.log('合并后的订单列表:', this.orderList)
				} catch (error) {
					console.error('获取订单失败:', error)
					this.orderList = []
				}
			}
		},

		// Swiper 滑动时触发
		swiperChange(e) {
			this.currentTab = e.detail.current
		},

		// 页面跳转
		navigateTo(url) {
			uni.navigateTo({
				url: url
			})
		},
		// 根据状态获取订单
		async getOrder(status) {
			try {
				const res = await request({
					url: `/orders/status?status=${status}`,
					method: 'GET'
				})

				if (res.code == 200) {
					this.orderList = res.data || []
					console.log('this.orderList', this.orderList)
				} else {
					this.orderList = []
				}
			} catch (error) {
				console.error('获取订单失败:', error)
				this.orderList = []
			}
		},

		// 获取所有状态的订单数量
		async getAllOrderCounts() {
			try {
				// 为每个标签获取对应状态的订单数量
				const promises = this.tabs.map(async (tab) => {
					const statuses = Array.isArray(tab.status) ? tab.status : [tab.status]

					// 如果是数组状态，需要分别获取每个状态的订单然后合并
					const statusPromises = statuses.map(status =>
						request({
							url: `/orders/status?status=${status}`,
							method: 'GET'
						})
					)

					const statusResults = await Promise.all(statusPromises)

					// 计算总数量
					let totalCount = 0
					statusResults.forEach(res => {
						if (res.code === 200 && res.data) {
							totalCount += res.data.length
						}
					})

					return totalCount
				})

				const results = await Promise.all(promises)

				// 更新每个标签的订单数量
				results.forEach((count, index) => {
					this.tabs[index].num = count
				})

				console.log('更新后的tabs:', this.tabs)
			} catch (error) {
				console.error('获取订单数量失败:', error)
				// 失败时将所有数量设为0
				this.tabs.forEach(tab => {
					tab.num = 0
				})
			}
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				0: '待付款',
				1: '待使用',
				2: '已发货',
				3: '待评价',
				4: '已关闭',
				5: '已取消',
				6: '退款中',
				7: '已退款'
			}
			return statusMap[status] || '未知状态'
		},

		// 取消订单
		cancelOrder(order) {
			order.order.status = 5
			uni.showModal({
				title: '提示',
				content: '确定要取消订单吗？',
				success: async (res) => {
					if (res.confirm) {
						// 执行取消订单逻辑
						const res = request({
							url: '/orders/putOrderByOn',
							method: 'PUT',
							data: order.order
						}).then(res => {
							if (res.code == 200) {
								setTimeout(() => {
									uni.showToast({
										title: '订单取消成功',
										icon: 'success'
									});
								}, 500);
								this.getOrderList()
							}
						});
						console.log('取消订单', order)
						// 刷新当前状态的订单列表
						this.getOrder(this.tabs[this.currentTab].status)
						// 更新所有状态的订单数量
						await this.getAllOrderCounts()
					}
				}
			})
		},

		// 修改订单
		modifyOrder(order) {
			// 修改订单逻辑
			console.log('修改订单', order)
			// 跳转到订单修改页面（复用createOrder页面）
			uni.navigateTo({
				url: `/public/order/createOrder?orderId=${order.order.id}&mode=edit`
			})
		},

		// 去支付
		goToPay(order) {
			// 支付逻辑
			console.log('去支付', order)
			// 可以跳转到支付页面
			uni.navigateTo({
				url: `/pages/payment/index?orderId=${order.id}&amount=${order.totalAmount}`
			})
		},

		initNavbarHeight() {
			// 使用全局注册的navbarUtil方法
			this.statusBarHeight = this.$navbarUtil.getStatusBarHeight()
			this.navbarHeight = this.$navbarUtil.getNavbarHeight()
			this.navbarTotalHeight = this.$navbarUtil.getNavbarTotalHeight()

			console.log('商户页面 - 导航栏高度:', {
				statusBarHeight: this.statusBarHeight,
				navbarHeight: this.navbarHeight,
				navbarTotalHeight: this.navbarTotalHeight
			})
		},
	},



	async onLoad() {
		this.initNavbarHeight()
		// 首先获取所有状态的订单数量
		await this.getAllOrderCounts()
		// 然后获取默认状态（待付款）的订单列表
		this.getOrder(0)
	}
}
</script>

<style lang="scss" scoped>
.content-area {}

.mine-order {
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 1000;

	.nav-left,
	.nav-right {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.back-icon,
		.more-icon {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
			line-height: 1;
		}

		.back-icon {
			font-size: 40rpx;
		}

		.more-icon {
			font-size: 28rpx;
			letter-spacing: -2rpx;
		}
	}

	.nav-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		text-align: center;
	}
}

/* 订单标签页样式 */
.order-tabs {
	height: 60px;
	display: flex;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	position: fixed;
	top: 0rpx; // 具体偏移由内联样式覆盖
	left: 0;
	right: 0;
	z-index: 999;
	padding: 10rpx 20rpx;

	.tab-item {
		flex: 1;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		cursor: pointer;

		.tab-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			position: relative;

			.tab-icon {
				margin-bottom: 8rpx;
				transition: all 0.3s ease;
			}

			.tab-title {
				font-size: 24rpx;
				color: #666;
				text-align: center;
				line-height: 1.2;
			}

			.tab-num {
				position: absolute;
				top: -10rpx;
				right: -20rpx;
				background-color: #ff4444;
				color: #fff;
				font-size: 20rpx;
				padding: 4rpx 8rpx;
				border-radius: 20rpx;
				width: 25rpx;
				height: 25rpx;
				line-height: 24rpx;
				text-align: center;
			}
		}

		&.active {
			.tab-content {
				.tab-icon {
					transform: scale(1.1);
				}

				.tab-title {
					color: #f27b1d;
					font-weight: 300;
				}
			}
		}
	}
}

/* 订单内容区域 */
.order-content {
	/* 具体偏移与高度通过内联样式动态适配 */
	padding: 20rpx;

	.tabs-content {
		width: 100%;

		.page-section {
			width: 100%;
		}
	}
}

/* 空状态样式 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	color: #999;

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 30rpx;
		opacity: 0.3;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
}

/* 订单卡片样式 */
.order-card {
	background: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 0;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
}

/* 订单头部 */
.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;

	.header-left {
		display: flex;
		align-items: center;
		gap: 10rpx;

		.header-tag {
			width: 10rpx;
			height: 20px;
			background-color: #f27b1d;
			border-radius: 10rpx;
		}

		.merchant-name {
			font-size: 32rpx;
			color: #333;
			font-weight: 500;

		}

		.play-icon {
			color: #666;
			font-size: 24rpx;
		}
	}

	.header-right {
		display: flex;
		align-items: center;
		gap: 10rpx;

		.status-badge {
			background: #fc4735;
			border-radius: 6rpx;
			padding: 8rpx 16rpx;

			.status-text {
				color: #fff;
				font-size: 24rpx;
			}
		}

		.countdown-badge {
			.countdown-text {
				color: #fc4735;
				font-size: 24rpx;
				font-weight: 500;
			}
		}
	}
}

/* 产品卡片 */
.order-product-card {
	margin: 0;

	box-shadow: none;
	border-radius: 0;
	background: transparent;
}

/* 已选班期 */
.selected-period {
	display: flex;
	align-items: center;
	gap: 20rpx;
	padding: 20rpx;
	border-top: 1rpx solid #f0f0f0;
	border-bottom: 1rpx solid #f0f0f0;

	.period-icon {
		width: 40rpx;
		height: 40rpx;

	}

	.period-label {
		font-size: 28rpx;
		color: #666;
		font-weight: bold;
	}

	.period-date {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}
}

/* 参营人员部分 */
.participants-section {
	padding: 20rpx;

	.section-header {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 20rpx;

		.cuIcon-peoplefill {
			font-size: 32rpx;
			color: #666;
			margin-right: 20rpx;
		}

		.section-title {
			font-size: 28rpx;
			color: #666;
			font-weight: bold;
		}
	}

	.participants-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;

		.participant-item {
			display: flex;
			justify-content: space-between;
			align-items: center;

			border-radius: 8rpx;

			.participant-info {
				display: flex;
				align-items: center;
				flex: 1;
				gap: 20rpx;

				.participant-name {
					font-size: 28rpx;
					color: #333;
				}

				.cuIcon-female,
				.cuIcon-male {
					font-size: 24rpx;
				}

				.gender-badge {
					font-size: 24rpx;
					color: #2ebdff;
				}

				.age-badge {
					background: #f27b1d;
					color: #fff;
					padding: 4rpx 12rpx;
					border-radius: 12rpx;
					font-size: 20rpx;
				}

				.participant-type {
					font-size: 24rpx;
					color: #666;
				}
			}

			.warning-icon {
				width: 40rpx;
				height: 40rpx;
				background: #fc4735;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;

				.cuIcon-warning {
					color: #fff;
					font-size: 24rpx;
				}
			}
		}
	}
}

/* 订单底部 */
.order-footer {
	padding: 20rpx;
	border-top: 1rpx solid #f0f0f0;

	.total-amount {
		text-align: right;
		margin-bottom: 30rpx;

		.amount-label {
			display: block;
			font-size: 24rpx;
			color: #666;
			margin-bottom: 8rpx;
		}

		.amount-value {
			font-size: 36rpx;
			color: #fc4735;
			font-weight: 600;
		}
	}

	.action-buttons {
		display: flex;
		justify-content: space-between;
		gap: 20rpx;
	}

	.amount-info {
		display: flex;
		padding: 10rpx;
		gap: 10rpx;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.btn-cancel {
		width: 120px;
		height: 80rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		border: 2rpx solid #fc4735;
		background: #fff;
		border-color: #ccc;
		color: #666;
	}

	.btn-pay {
		width: 120px;
		height: 80rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		border: 2rpx solid #fc4735;
		background: #fff;
		border-color: #fc4735;
		color: #fc4735;
	}

	.action-buttons-one {
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 20rpx;
	}

	.more {
		font-size: 26rpx;
		color: #999;
	}

	.action-buttons-one-right {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		gap: 20rpx;

	}

	.btn-sumit {
		width: 120px;
		height: 80rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		border: 2rpx solid #0081ff;
		background: #0081ff;
		color: #fff;
	}

}
</style>